var currentPoint;//当前地图的坐标点
var currentMarker;//当前地图的标注点
var currentMarkerIcon;//当前地图的标注点图标
(function () {
    //创建并初始化地图对象
    var currentRegion = '河北省邯郸市魏县';//地图显示的行政区域
    var zoomLevel = 11;//地图缩放级别
    var centerPoint = new BMap.Point(114.954647, 36.248889);//地图中心点坐标
    var map = new BMap.Map("allmap");// 创建Map实例,设置地图允许的最小/大级别
    var markerClusterer = new BMapLib.MarkerClusterer(map);
    var overlays = [];

    //地图相关的操作
    var mapOpts = {
        init: function (map) {
            map.centerAndZoom(centerPoint, zoomLevel);// 设置中心点坐标和地图级别。
            map.enableScrollWheelZoom();//启用地图滚轮缩放功能
            map.setMapStyle({style: "grayscale"});//设置地图主题样式
        },
        addMapRightMenu: function (map, rightMenuItem) {
            var menu = new BMap.ContextMenu();
            for (var i = 0; i < rightMenuItem.length; i++) {
                menu.addItem(new BMap.MenuItem(rightMenuItem[i].text, rightMenuItem[i].callback, 100));
            }
            map.addContextMenu(menu);
        },
        createBoundary: function (map) {//显示魏县行政边界轮廓
            var bdary = new BMap.Boundary();
            bdary.get(currentRegion, function (rs) {//获取行政区域
                //建立多边形覆盖物
                var ply = new BMap.Polyline(rs.boundaries[0], {strokeWeight: 2, strokeColor: "#ff0000"});
                //添加覆盖物
                map.addOverlay(ply);
            });
        },
        loadMarkPoits: function (pointType) {//加载所有标记的点
            map.clearOverlays();
            markerClusterer.clearMarkers();
            var url = "/povertyMap/queryMarkPoints";
            $.get(url, {pointType: pointType},
                function (rs) {
                    if (rs.status == 200) {
                        for (var i = 0; i < rs.result.length; i++) {
                            mapOpts.addMarkPoint(rs.result[i]);
                        }
                        //最简单的用法，生成一个marker数组，然后调用markerClusterer类即可。
                    }
                });
        },
        addMarkPoint: function (pointObj) {//添加标注点
            var point = new BMap.Point(pointObj.longitude, pointObj.latitude);
            var icon = new BMap.Icon(pointObj.icon, new BMap.Size(23, 23));
            var overlay = new BMap.Marker(point, {icon: icon});
            overlay.pointId = pointObj.id;
            overlay.pointType = pointObj.pointType;
            map.addOverlay(overlay);
            //标注注册点击事件
            markerPots.addEventListener(overlay);
            //标注增加右键菜单
            markerPots.addRightMenu(overlay, [markerRightMenuItems.editMarker, markerRightMenuItems.delMarker]);
            markerClusterer.addMarker(overlay);
        }
    };

    //标注点右键菜单元素
    var markerRightMenuItems = {
        newDelMarker: {
            text: '删除',
            callback: function () {
                var index = layer.confirm('确定要删除该标注点吗？', {
                    btn: ['确定', '取消'] //按钮
                }, function () {
                    map.removeOverlay(currentMarker);
                    markerClusterer.removeMarker(currentMarker);
                    layer.close(index);
                });
            }
        },
        delMarker: {
            text: '删除',
            callback: function () {
                var index = layer.confirm('确定要删除该标注点吗？', {
                    btn: ['确定', '取消'] //按钮
                }, function () {
                    $.post("/povertyMap/deletePointById", {
                        id: currentMarker.pointId
                    }, function (rs) {
                        if (rs.status == 200) {
                            map.removeOverlay(currentMarker);
                            markerClusterer.removeMarker(currentMarker);
                            layer.close(index);
                        } else {
                            alert(rs.message);
                        }
                    }, 'json');
                });
            }
        },
        editMarker: {
            text: '编辑',
            callback: function () {
                var url = '/templates/html/mapEditPoint.html';
                $.get(url, function (str) {
                    var layerDlg = layer.open({
                        type: 1,
                        title: '修改标注点信息',
                        content: str, //注意，如果str是object，那么需要字符拼接。
                        area: ['460px', '500px'],
                        btn: ['保存', '关闭'],
                        yes: function () {
                            mapEditPoint.save(currentPoint, layerDlg, currentMarker);
                        }
                    });

                    $("#villageQBtn").off("click");
                    $("#villageQBtn").on("click", function () {
                        url = '/templates/html/villageSelect.html';
                        $.get(url, function (str) {
                            var layerDlg = layer.open({
                                type: 1,
                                title: '村子信息（双击选择）',
                                content: str, //注意，如果str是object，那么需要字符拼接。
                                area: ['500px', '400px'],
                                btn: ['关闭']
                            });
                        });
                    });
                    $("#companyQBtn").off("click");
                    $("#companyQBtn").on("click", function () {
                        url = '/templates/html/companySelect.html';
                        companySelectDlg = layer.open({
                            type: 2,
                            title: '项目库信息',
                            content: url, //注意，如果str是object，那么需要字符拼接。
                            area: ['600px', '500px'],
                            btn: ['关闭'],
                            end: function () {
                                if (window.companySelectData) {
                                    $('#mapUpdatePointContainer input[name="infoId"]').val(window.companySelectData.id);//企业ID
                                    $('#mapUpdatePointContainer #companyInfo input[name="company_dm"]').val(window.companySelectData.company_dm);//企业代码
                                    $('#mapUpdatePointContainer #companyInfo input[name="company_name"]').val(window.companySelectData.company_name);//企业名称
                                    $('#mapUpdatePointContainer #companyInfo input[name="legal_person"]').val(window.companySelectData.legal_person);//法人
                                    $('#mapUpdatePointContainer #companyInfo input[name="tel"]').val(window.companySelectData.tel);//联系方式
                                    $('#mapUpdatePointContainer #companyInfo textarea[name="business_item"]').text(window.companySelectData.business_item);//经营项目
                                    $('#mapUpdatePointContainer #companyInfo input[name="active_staff"]').val(window.companySelectData.active_staff);//员工总数
                                    $('#mapUpdatePointContainer #companyInfo input[name="qzpk"]').val(window.companySelectData.qzpk);//全职贫困户
                                    $('#mapUpdatePointContainer #companyInfo input[name="lspk"]').val(window.companySelectData.lspk);//临时贫困户
                                    $('#mapUpdatePointContainer #companyInfo input[name="registered_fund"]').val(window.companySelectData.registered_fund);//投资总额
                                    $('#mapUpdatePointContainer #companyInfo a[name="link"]').text(window.companySelectData.link);//连接
                                    $('#mapUpdatePointContainer #companyInfo a[name="link"]').attr("href", window.companySelectData.link);//连接
                                    $('#mapUpdatePointContainer #companyInfo textarea[name="company_profile"]').text(window.companySelectData.company_profile);//企业介绍
                                }
                            }
                        });
                    });

                });
            }
        }
    };

    function mapNewPointViewInit(marker) {
        $("#mapNewPointContainer").off("change", ".select");
        $("#mapNewPointContainer").on("change", ".select", function () {
            var vals = $(this).val().split(",");
            if (vals[0].indexOf("village") > -1) {
                $('#mapNewPointContainer input[name="pointType"]').val(vals[0]);
                marker.pointType = vals[0];
                $("#mapNewPointContainer #companyInfo").hide();
                $("#mapNewPointContainer #villageInfo").show();
            } else if (vals[0].indexOf("company") > -1) {
                $('#mapNewPointContainer input[name="pointType"]').val(vals[0]);
                marker.pointType = vals[0];
                $("#mapNewPointContainer #villageInfo").hide();
                $("#mapNewPointContainer #companyInfo").show();
            } else {
                $("#mapNewPointContainer #villageInfo").hide();
                $("#mapNewPointContainer #companyInfo").hide();
            }
            marker.setIcon(new BMap.Icon(vals[1], new BMap.Size(23, 22)));
            marker.setOffset(new BMap.Size(5, -10));
            currentMarkerIcon = vals[1];
        });

        $("#villageQBtn").off("click");
        $("#villageQBtn").on("click", function () {
            url = '/templates/html/villageSelect.html';
            $.get(url, function (str) {
                var layerDlg = layer.open({
                    type: 1,
                    title: '村子信息（双击选择）',
                    content: str, //注意，如果str是object，那么需要字符拼接。
                    area: ['500px', '400px'],
                    btn: ['关闭']
                });
            });
        });
        $("#companyQBtn").off("click");
        $("#companyQBtn").on("click", function () {
            url = '/templates/html/companySelect.html';
            companySelectDlg = layer.open({
                type: 2,
                title: '项目库信息',
                content: url, //注意，如果str是object，那么需要字符拼接。
                area: ['600px', '500px'],
                btn: ['关闭'],
                end: function () {
                    if (window.companySelectData) {
                        $('#mapNewPointContainer input[name="infoId"]').val(window.companySelectData.id);//企业ID
                        $('#mapNewPointContainer #companyInfo input[name="company_dm"]').val(window.companySelectData.company_dm);//企业代码
                        $('#mapNewPointContainer #companyInfo input[name="company_name"]').val(window.companySelectData.company_name);//企业名称
                        $('#mapNewPointContainer #companyInfo input[name="legal_person"]').val(window.companySelectData.legal_person);//法人
                        $('#mapNewPointContainer #companyInfo input[name="tel"]').val(window.companySelectData.tel);//联系方式
                        $('#mapNewPointContainer #companyInfo textarea[name="business_item"]').text(window.companySelectData.business_item);//经营项目
                        $('#mapNewPointContainer #companyInfo input[name="active_staff"]').val(window.companySelectData.active_staff);//员工总数
                        $('#mapNewPointContainer #companyInfo input[name="qzpk"]').val(window.companySelectData.qzpk);//全职贫困户
                        $('#mapNewPointContainer #companyInfo input[name="lspk"]').val(window.companySelectData.lspk);//临时贫困户
                        $('#mapNewPointContainer #companyInfo input[name="registered_fund"]').val(window.companySelectData.registered_fund);//投资总额
                        $('#mapNewPointContainer #companyInfo a[name="link"]').text(window.companySelectData.link);//投资总额
                        $('#mapNewPointContainer #companyInfo a[name="link"]').attr("href", window.companySelectData.link);//投资总额
                        $('#mapNewPointContainer #companyInfo textarea[name="company_profile"]').text(window.companySelectData.company_profile);//企业介绍

                    }
                }
            });
        });
    }

    //标注点相关操作
    var markerPots = {
        addRightMenu: function (marker, rightMenuItem) {
            var menu = new BMap.ContextMenu();
            for (var i = 0; i < rightMenuItem.length; i++) {
                menu.addItem(new BMap.MenuItem(rightMenuItem[i].text, rightMenuItem[i].callback, 100));
            }
            marker.addContextMenu(menu);
            marker.addEventListener('rightclick', function (e) {
                currentMarker = e.target;//更新当前地图坐标点为鼠标右键位置
            });
        },
        markerClick: function (marker) {
            var url = "";
            if (marker.isNew) {
                url = '/templates/html/mapAddPoint.html';
                $.get(url, function (str) {
                    var layerDlg = layer.open({
                        type: 1,
                        title: '新增标注点信息',
                        content: str, //注意，如果str是object，那么需要字符拼接。
                        area: ['600px', '500px'],
                        btn: ['保存', '关闭'],
                        yes: function () {
                            mapAddPoint.save(currentPoint, layerDlg, marker);
                        }
                    });
                    mapNewPointViewInit(marker);
                });
            } else {
                url = '/templates/html/mapPoint.html';
                $.get(url, {id: marker.pointId}, function (str) {
                    var point = new BMap.Point(marker.getPosition().lng, marker.getPosition().lat);
                    var infoWindow = new BMap.InfoWindow(str, {
                        width: 450,     // 信息窗口宽度
                        height: 370,     // 信息窗口高度
                        enableMessage: false//设置允许信息窗发送短息
                    });  // 创建信息窗口对象
                    map.openInfoWindow(infoWindow, point); //开启信息窗口

                    $.get("/povertyMap/mapPointInfo", {
                        pointId: marker.pointId,
                        pointType: marker.pointType
                    }, function (rs) {
                        if (marker.pointType.indexOf('company') > -1) {
                            $('#mapPointInfoContainer #companyInfo').show();
                            $('#mapPointInfoContainer input[name="infoId"]').val(rs.id);//企业名称
                            $('#mapPointInfoContainer #companyInfo input[name="company_dm"]').val(rs.company_dm);//企业代码
                            $('#mapPointInfoContainer #companyInfo input[name="company_name"]').val(rs.company_name);//企业名称
                            $('#mapPointInfoContainer #companyInfo input[name="legal_person"]').val(rs.legal_person);//法人
                            $('#mapPointInfoContainer #companyInfo input[name="tel"]').val(rs.tel);//联系方式
                            $('#mapPointInfoContainer #companyInfo textarea[name="business_item"]').text(rs.business_item);//经营项目
                            $('#mapPointInfoContainer #companyInfo input[name="active_staff"]').val(rs.active_staff);//员工总数
                            $('#mapPointInfoContainer #companyInfo input[name="qzpk"]').val(rs.qzpk);//全职贫困户
                            $('#mapPointInfoContainer #companyInfo input[name="lspk"]').val(rs.lspk);//临时贫困户
                            $('#mapPointInfoContainer #companyInfo input[name="registered_fund"]').val(rs.registered_fund);//投资总额
                            $('#mapPointInfoContainer #companyInfo a[name="link"]').text(rs.link);//连接
                            $('#mapPointInfoContainer #companyInfo a[name="link"]').attr("href", rs.link);//连接
                            $('#mapPointInfoContainer #companyInfo textarea[name="company_profile"]').text(rs.company_profile);//企业介绍

                        }
                    }, 'json');
                });
            }
        },
        addEventListener: function (marker) {
            marker.addEventListener("click", function (e) {
                markerPots.markerClick(e.target);
            });
        }
    };
    //地图注册右键事件
    map.addEventListener('rightclick', function (e) {
        currentPoint = e.point;//更新当前地图坐标点为鼠标右键位置
        map.removeOverlay(overlays[0]);
    });

    mapOpts.init(map);
    mapOpts.createBoundary(map);
    mapOpts.addMapRightMenu(map, [
        {
            text: '添加标注',
            callback: function () {
                //创建标注点
                var overlay = new BMap.Marker(currentPoint);
                overlay.isNew = true;
                //添加标注
                map.addOverlay(overlay);
                markerClusterer.addMarker(overlay);
                //标注注册点击事件
                markerPots.addEventListener(overlay);
                //标注增加右键菜单
                markerPots.addRightMenu(overlay, [markerRightMenuItems.newDelMarker]);
            }
        }
    ]);
    mapOpts.loadMarkPoits("all");

    var mapAddPoint = {
        save: function (currentPoint, layerDlg, marker) {
            $.post("/povertyMap/addPoint", {
                longitude: currentPoint.lng,
                latitude: currentPoint.lat,
                icon: currentMarkerIcon,
                pointType: $('#mapNewPointContainer input[name="pointType"]').val(),
                infoId: $('#mapNewPointContainer input[name="infoId"]').val()
            }, function (rs) {
                if (rs.status == 200) {
                    marker.isNew = false;
                    marker.pointId = rs.result;//返回新增的ID
                    markerPots.addRightMenu(marker, [markerRightMenuItems.editMarker, markerRightMenuItems.delMarker]);
                    layer.close(layerDlg);
                } else {
                    alert(rs.message);
                }
            }, 'json');
        }
    };
    var mapEditPoint = {
        save: function (currentPoint, layerDlg, marker) {
            $.post("/povertyMap/updatePoint", {
                id: marker.pointId,
                infoId: $('#mapUpdatePointContainer input[name="infoId"]').val()
            }, function (rs) {
                if (rs.status == 200) {
                    layer.close(layerDlg);
                } else {
                    alert(rs.message);
                }
            }, 'json');
        }
    };


    // 定义一个控件类,即function
    function AddressSearchControl() {
        this.defaultAnchor = BMAP_ANCHOR_TOP_LEFT;
        this.defaultOffset = new BMap.Size(10, 10);
    }

    // 通过JavaScript的prototype属性继承于BMap.Control
    AddressSearchControl.prototype = new BMap.Control();

    // 自定义控件必须实现自己的initialize方法,并且将控件的DOM元素返回
    // 在本方法中创建个p元素作为控件的容器,并将其添加到地图容器中
    AddressSearchControl.prototype.initialize = function (map) {
        // 创建一个DOM元素
        var p = document.createElement("p");
        p.innerHTML = '<p id="r-result"><input type="text" id="suggestId" placeholder="搜索地址" size="20" value="百度" style="width:150px;" /></p><p id="searchResultPanel" style="border:1px solid #C0C0C0;width:150px;height:auto; display:none;"></p>';
        // 添加DOM元素到地图中
        map.getContainer().appendChild(p);
        // 将DOM元素返回
        return p;
    };

    function ShowLegendControl() {
        this.defaultAnchor = '';
        this.defaultOffset = new BMap.Size(5, 5);// 默认偏移量
    }

    ShowLegendControl.prototype = new BMap.Control();
    ShowLegendControl.prototype.initialize = function (map) {
        // 创建一个DOM元素
        var ul = document.createElement("ul");
        ul.style.background = "White";
        ul.style.padding = "15px";
        ul.style.opacity = " 0.8";
        ul.id = "mapLeg";
        var li = $("<li><b>图例</b>:<br></li>").appendTo(ul);
        // var li = $("<li class='ml-item' type='village_zrc'><img src='/img/map/cursor_02.png'/>&nbsp;<b>自然村</b></li>").appendTo(ul);
        var li = $("<li class='ml-item' type='village_pkc'><img class='aaa' src='/img/map/cursor_02.png'/>&nbsp;<b>贫困户</b></li>").appendTo(ul);
        var li = $("<li class='ml-item' type='company_wgc'><img src='/img/map/cursor_05.png'/>&nbsp;<b>微工厂</b></li>").appendTo(ul);
        var li = $("<li class='ml-item' type='company_nyyq'><img src='/img/map/cursor_03.png'/>&nbsp;<b>生态园区</b></li>").appendTo(ul);
        var li = $("<li class='ml-item' type='company_ltqy'><img src='/img/map/cursor_06.png'/>&nbsp;<b>龙头企业</b></li>").appendTo(ul);
        // 添加DOM元素到地图中
        map.getContainer().appendChild(ul);
        // 将DOM元素返回
        return ul;
    };

    // 创建控件
    var myZoomCtrl = new AddressSearchControl();
    myZoomCtrl.defaultOffset = new BMap.Size(10, 18);
    // 添加到地图当中
    map.addControl(myZoomCtrl);
    // 创建控件
    var showLegendCtrl = new ShowLegendControl();
    // 添加到地图当中
    map.addControl(showLegendCtrl);

    //图例元素点击时所作的操作
    $("#mapLeg .ml-item").on("click", function () {
        if ($(this).hasClass("ml-item-active")) {
            $(this).removeClass("ml-item-active");
        } else {
            $(this).addClass("ml-item-active");
        }
        if ($("li.ml-item-active").length > 0) {
            var types = '';
            $.each($("li.ml-item-active"), function (i, n) {
                types += $(n).attr("type") + ",";
            });
            mapOpts.loadMarkPoits(types.substr(0, types.length - 1));
            mapOpts.createBoundary(map);
        } else {
            mapOpts.loadMarkPoits("all");
            mapOpts.createBoundary(map);
        }
    });

    var ac = new BMap.Autocomplete({"input": "suggestId", "location": map});//建立一个自动完成的对象

    ac.addEventListener("onhighlight", function (e) {  //鼠标放在下拉列表上的事件
        var str = "";
        var _value = e.fromitem.value;
        var value = "";
        if (e.fromitem.index > -1) {
            value = _value.province + _value.city + _value.district + _value.street + _value.business;
        }
        str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;

        value = "";
        if (e.toitem.index > -1) {
            _value = e.toitem.value;
            value = _value.province + _value.city + _value.district + _value.street + _value.business;
        }
        str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;
        G("searchResultPanel").innerHTML = str;
    });

    var myValue;
    ac.addEventListener("onconfirm", function (e) {    //鼠标点击下拉列表后的事件
        var _value = e.item.value;
        myValue = _value.province + _value.city + _value.district + _value.street + _value.business;
        G("searchResultPanel").innerHTML = "onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue;

        setPlace();
    });

    function setPlace() {
        function myFun() {
            var pp = local.getResults().getPoi(0).point;    //获取第一个智能搜索的结果
            map.centerAndZoom(pp, 13);//将地图视野推近到点击位置
            var overlay = new BMap.Marker(pp);
            map.removeOverlay(overlays[0]);
            map.addOverlay(overlay);    //添加标注
            overlays[0] = overlay;//保存标注结果
        }

        var local = new BMap.LocalSearch(map, { //智能搜索
            onSearchComplete: myFun
        });
        local.search(myValue);
    }

    function G(id) {
        return document.getElementById(id);
    }

})();


